package com.jetpackframework.webview;

import android.os.RemoteException;
import android.util.Log;

import com.jetpackframework.IMainProcessToWebViewInsterface;
import com.jetpackframework.IWebViewToMainProcessInsterface;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

public class WebViewCommandManager extends IWebViewToMainProcessInsterface.Stub {
    private static WebViewCommandManager manager;
    private Map<String,IWebViewCommand> mWebViewCommands;
    private WebViewCommandManager(){
        ServiceLoader<IWebViewCommand> loader = ServiceLoader.load(IWebViewCommand.class);
        Iterator<IWebViewCommand> iterator = loader.iterator();
        mWebViewCommands = new HashMap<>();
        while (iterator.hasNext()){
            IWebViewCommand webViewCommand = iterator.next();
            if (!mWebViewCommands.containsKey(webViewCommand.commandName())){
                mWebViewCommands.put(webViewCommand.commandName(),webViewCommand);
            }
        }
    }
    public static synchronized WebViewCommandManager getInstance() {
        if (manager == null){
            manager = new WebViewCommandManager();
        }
        return manager;
    }

    @Override
    public void handleWebViewCommand(String command, String params,String callName, IMainProcessToWebViewInsterface mpwv) throws RemoteException {
        Log.e("TAG","handleWebViewCommand command="+command+",params="+params+",callName="+callName);
        IWebViewCommand iWebViewCommand = mWebViewCommands.get(command);
        if (iWebViewCommand != null){
            iWebViewCommand.execCommand(params,callName,mpwv);
        }
    }
}
